package top.maochang.hou.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public  class BaseServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //1.获取请求路径
            String uri = request.getRequestURI();
            System.err.println(uri);
            if(uri.contains("/assets")){
                return;
            }
            //2.截取最后一段请求路径
            int index = uri.lastIndexOf('/');
            String methodName = uri.substring(index + 1);
            System.err.println(methodName);
            //3.开始反射
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            System.out.println(method);
            //4.私有方法强制反射
            method.setAccessible(true);
            //5.调用目标方法开始执行
            method.invoke(this,request,response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);// 把异常抛给 Filter 过滤器
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
